package com.appkubes.fintech.restful.config.advise;

import com.appkubes.fintech.common.exption.BusinessException;
import com.appkubes.fintech.common.response.Response;
import com.appkubes.fintech.common.response.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * @author Jiahong Chen
 * @date 2019/10/31
 */
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class AdviseExceptionHandler {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    Response handleException(HttpServletRequest request, Exception e) {
        log.error("错误clientIp : {}, 请求url : {}, 参数 : {}",request.getRemoteAddr(), request.getRequestURL().toString(), request.getParameterMap().entrySet().stream().map(n -> n.getKey()+"[" + n.getValue()[0] + "]").collect(Collectors.toList()).toString());
        log.error("异常信息:", e);
        if (e instanceof BusinessException) {
            BusinessException be = (BusinessException)e;
            return new Response(be.getCode().getCode(), be.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            return new Response(ResponseCode.PARAM_FAIL, ((MethodArgumentNotValidException)e).getBindingResult().getFieldError().getDefaultMessage());
        }
        return new Response(ResponseCode.SYS_FAIL, "系统异常");
    }
}
